package com.inspur.icity.bus.base.core.service;

import org.apache.commons.io.FileUtils;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.AesCipherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.Key;

/**
 * AES 加密解密工具类
 */
public class AesService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    private static final String keyFileName = "aes.key";
    private static AesCipherService aesCipherService;
    private static byte[] keyBytes = null;

    public AesService() {
        logger.info("AesService 开始初始化...");
        aesCipherService = new AesCipherService();
        aesCipherService.setKeySize(128); //设置key长度
        try {
            InputStream input = getClass().getClassLoader().getResourceAsStream(keyFileName);
            keyBytes = input2byte(input);
            logger.info("密钥文件加载完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("AesService 初始化结束！");
    }

    /**
     * 生成新的AES加密密钥
     * @param keyFileName
     */
    public void generateNewKey(String keyFileName) {
        Key key = aesCipherService.generateNewKey();
        File keyFile = new File(keyFileName);
        try {
            FileUtils.writeByteArrayToFile(keyFile, key.getEncoded());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 加密
     * @param text
     * @return
     */
    public String encrypt(String text) {
        if (keyBytes == null || text == null) {
            return null;
        }
        String encryptText = aesCipherService.encrypt(text.getBytes(), keyBytes).toHex();
        return encryptText;
    }

    /**
     * 解密
     * @param encryptText
     * @return
     */
    public String decrypt(String encryptText) {
        if (keyBytes == null || encryptText == null) {
            return null;
        }
        String text = new String(aesCipherService.decrypt(Hex.decode(encryptText), keyBytes).getBytes());
        return text;
    }

    public static final byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }
}
